import React from "react";
import {Modal, Input, Button, Table, Radio, Form, Spin, Checkbox, Select, Icon, Popover, Tooltip} from "antd";
import {connect} from "dva";
import ReactJson from "react-json-view";
import styles from "./index.less";

import {openNotificationWithIcon} from "../../utils/comm";

const formItemLayout = {
  labelCol: {span: 9},
  wrapperCol: {span: 13},
};
const formItemLayout2 = {
  labelCol: {span: 11},
  wrapperCol: {span: 11},
};
const formItemLayout3 = {
  labelCol: {span: 7},
  wrapperCol: {span: 15},
};
const buttonItemLayout = {
  wrapperCol: {span: 14, offset: 3},
};

const {Option} = Select;

@Form.create()
@connect(({FormSelectModel, loading, FlowChart}) => ({
  loading,
  FormSelectStore: FormSelectModel,
  FlowChartStore: FlowChart,
}))

class FlowFormSelect extends React.Component {
  constructor(props) {
    const {selectedModel = {}} = props;
    const {
      model: {properties: {displayStyle = ""} = {}} = {},
    } = selectedModel;
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.state = {
      selectFormData: null,
      selectedRowKeys: [],
      page: {
        pageNum: 1,
        pageSize: 6,
      },
      activeKey: "1",
      checked: true,
      formDescriptionUrl: "",
      selected: displayStyle || "",
      formContent: "",
      viewFormVisible: false,
      result: [],
      // quanXian: [],
      // formSource:'',
    };
    this.queryParam = {
      searchName: "",
    };
    this.columns = [
      {
        title: "表单名称",
        dataIndex: "formName",
        key: "formName",
        width: "35%",
        render: text => {
          return (
            <span style={{wordWrap: "break-word", wordBreak: "break-all "}}>
              {text}
            </span>
          );
        },
      },
      {
        title: "表单编码",
        dataIndex: "formKey",
        key: "formKey",
      },
      {
        title: "创建人",
        dataIndex: "creatorName",
        key: "creatorName",
        width: "20%",
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        key: "createTime",
        width: "25%",
      },
    ];

    this.columnsExternal = [
      {
        title: "编号",
        dataIndex: "id",
        key: "id",
      },
      {
        title: "表单名称",
        dataIndex: "formName",
        key: "formName",
        render: text => {
          return (
            <span style={{wordWrap: "break-word", wordBreak: "break-all "}}>
              {text}
            </span>
          );
        },
      },
      {
        title: "版本",
        dataIndex: "version",
        key: "version",
      },
      {
        title: "创建人",
        dataIndex: "founder",
        key: "founder",
      },
      {
        title: "创建时间",
        dataIndex: "createdTime",
        key: "createdTime",
      },
      {
        title: "操作",
        // eslint-disable-next-line no-unused-vars
        render: (text, record) => {
          return <a>查看</a>;
        },
      },
    ];
  }

  // dispatch={dispatch}
  // visible={formVisible}
  // selectData={formkeydefinition}
  // onCancel={() => this.handleformVisible(false)}
  // formSelect={this.handleFormSelect}

  componentDidMount() {
    const externalForm = this.props.isCanvas ? (this.props.modelProperties.formSource == 'externalForm' ? "2" : "1") : (this.props.selectedModel.model.properties.formSource == 'externalForm' ? "2" : "1");
    this.setState({activeKey: externalForm});
    const {
      dispatch,
      isNodes,
      selectedModel = {},
      modelProperties,
    } = this.props;
    const {formkeydefinition = ""} = modelProperties;
    const {
      model: {
        properties: {formkeydefinition: nodesFormkeydefinition = ""} = {},
      } = {},
    } = selectedModel;
    this.initFormData();
    if (formkeydefinition || nodesFormkeydefinition) {
      dispatch({
        type: "FormConfigure/getExternalFormDetail",
        payload: {
          formKey: isNodes ? nodesFormkeydefinition : formkeydefinition,
        },
      }).then(({errCode, datas}) => {
        if (errCode === 0) {
          this.setState({
            formDescriptionUrl: datas.formDescriptionUrl,
          });
        }
      });
    }
  }

  componentWillUnmount() {
  }

  getParams = () => {
    const {page, activeKey} = this.state;
    const {extraParam} = this.props;
    // status: 1 已启用的表单
    return {...page, ...this.queryParam, activeKey, ...extraParam, status: 1};
  };

  getPageSelectData = () => {
    const {selectFormData} = this.state;
    const {selectData} = this.props;
    if (selectFormData) {
      return selectFormData.formKey;
    }
    return selectData;
  };

  initFormData = () => {
    const params = this.getParams();
    const {dispatch} = this.props;
    dispatch({type: "FormSelectModel/getListData", payload: params}).then(
      ({errCode, errMsg, errortext}) => {
        if (errCode !== 0) {
          this.openNotificationWithIcon(
            "warning",
            "",
            errMsg || errortext || "获取表单信息失败",
          );
        }
      },
    );
  };

  handleTableChange = pagination => {
    const {
      page: {pageSize},
    } = this.state;
    let newCurrent = pagination.current;
    if (pagination.pageSize !== pageSize) {
      newCurrent = 1;
    }
    this.setState(
      {page: {pageNum: newCurrent, pageSize: pagination.pageSize}},
      () => {
        this.initFormData();
      },
    );
  };

  handleSearch = () => {
    const {page} = this.state;
    this.setState({page: {...page, pageNum: 1}}, () => {
      this.initFormData();
    });
  };

  handleInputChange = e => {
    const obj = {searchName: e.target.value};
    this.queryParam = {...this.queryParam, ...obj};
  };
  // Source = (data)=>{
  //   // console.log(data)
  //   this.setState({
  //     formSource: data,
  //   })
  // }

  handleOk = () => {
    const {
      formDetailSelect,
      formSelect,
      selectData = "",
      selectFormData: defaultFormData = {},
      dispatch,
      getDatas,
      // modelProperties,
      // Source,
    } = this.props;
    // Source('innerForm')
    const {selectFormData} = this.state;
    if (formSelect) {
      const resData = selectFormData ? selectFormData.formKey : selectData;
      formSelect(resData);
      this.resetSelect();
    } else if (formDetailSelect) {
      const resData = selectFormData || defaultFormData;
      formDetailSelect(resData);
      this.resetSelect();
      // 判断是否请求FormSetupInfo的数据
      dispatch({
        type: "FormSelectModel/FormSetupInfo",
        payload: {formId: resData.formId},
      }).then(({errCode, datas}) => {
        if (errCode === 0) {
          formDetailSelect({...resData, formFields: datas});
          getDatas(datas);
        }
      });
    }
  };

  handleFormOk = e => {
    if (e && e.preventDefault) e.preventDefault();
    const {
      form,
      dispatch,
      onCancel,
      externalFormDetailSelect,
      processExternalFormDetailSelect,
      isCanvas,
      getDatas,
      // Source,
    } = this.props;

    const {activeKey} = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        const formPayload = {
          formDescriptionUrl: values.formDescriptionUrl,
        };
        if (activeKey === "2") {
          dispatch({
            type: "FormSelectModel/getExternalFormInfo",
            payload: formPayload,
          }).then(({errCode, errMsg, datas, errortext}) => {
            if (errCode === 0) {
              if (!isCanvas && externalFormDetailSelect) {
                externalFormDetailSelect({
                  datas,
                  displayStyle: values.displayStyle,
                  showAsUrl: values.showAsUrl === true ? "Y" : "N",
                });
                getDatas(datas)
                // Source('externalForm')

              } else if (isCanvas && processExternalFormDetailSelect) {
                getDatas(datas?.formFields)
                processExternalFormDetailSelect(datas);
              }
              onCancel();
            } else {
              this.openNotificationWithIcon(
                "warning",
                "",
                errMsg || errortext || "获取外置表单信息失败",
              );
            }
            // eslint-disable-next-line no-debugger
          });
        } else if (externalFormDetailSelect) {
          const {
            existingForm = "",
            existingDisplayStyle,
            existingShowAsUrl,
          } = values;
          const _existingForm = JSON.parse(existingForm);
          externalFormDetailSelect({
            datas: {
              formKey: _existingForm.formkeydefinition,
              formName: _existingForm.formname,
              formId: _existingForm.formId,
            },
            displayStyle: existingDisplayStyle === true ? "standard" : "empty",
            showAsUrl: existingShowAsUrl === true ? "Y" : "N",
          });
        }
      }
    });
  };

  handleCancel = () => {
    const {onCancel} = this.props;
    if (onCancel) {
      onCancel();
    }
    this.resetSelect();
  };

  resetSelect = () => {
    this.setState({selectFormData: null, selectedRowKeys: []});
  };

  onRadioChange = e => {
    if (e.target.value === "1") {
      this.queryParam = {...this.queryParam, searchName: ""};
      this.setState(
        {activeKey: e.target.value, page: {pageSize: 6, pageNum: 1}},
        () => {
          this.initFormData();
        },
      );
    } else {
      this.setState({activeKey: e.target.value, checked: false});
      // this.openNotificationWithIcon("warning", "", "标准版本不支持外置表单");
    }
  };

  handleCheckOnChange = e => {
    this.setState({checked: e.target.checked});
  };

  handleChange = value => {
    this.setState({selected: value});
  };

  viewForm = () => {
    const {form, dispatch} = this.props;
    const val = form.getFieldValue("formDescriptionUrl");
    if (val === "") {
      this.openNotificationWithIcon("warning", "", "请输入表单地址");
    } else {
      dispatch({
        type: "FormSelectModel/viewExternalFormInfo",
        payload: {formDescriptionUrl: val},
      }).then(({errCode, errMsg, datas, errortext}) => {
        if (errCode === 0) {
          this.setState({
            formContent: datas,
            viewFormVisible: true,
          });
        } else {
          this.openNotificationWithIcon(
            "warning",
            "",
            errMsg || errortext || "查看表单解析内容失败",
          );
        }
      });
    }
  };

  // 查看表单解析内容弹窗
  handleViewFormVisible = visible => {
    this.setState({viewFormVisible: visible});
  };

  handleFocus = () => {
    const {flowEditRef, modelProperties} = this.props;
    const data = flowEditRef.getDrawData();
    const result = [];
    result.push(modelProperties);
    // eslint-disable-next-line no-unused-expressions
    data?.nodes
      .filter(v => v.shape !== "StartNoneEvent" && v.shape !== "EndNoneEvent")
      .map(item => {
        const {model: {properties = {}} = {}} = item;
        result.push(properties);
        return null;
      });
    this.setState({
      result,
    });
  };

  render() {
    const {
      visible,
      loading: {effects},
      FormSelectStore,
      form,
      isCanvas,
      selectedModel = {},
    } = this.props;

    const {
      model: {properties: {displayStyle = "", showAsUrl = ""} = {}} = {},
    } = selectedModel;
    const {getFieldDecorator} = form;
    const {totalCount, listData = []} = FormSelectStore;
    const {
      page: {pageNum, pageSize},
      selectedRowKeys,
      activeKey,
      checked,
      formDescriptionUrl,
      selected,
      viewFormVisible,
      formContent,
      result,
    } = this.state;
    const dataLoading = effects["FormSelectModel/getListData"] || false;
    const rowKey = this.getPageSelectData();

    const title = (
      <div>
        <span>表单引用</span>

        <Radio.Group
          onChange={this.onRadioChange}
          value={activeKey}
          style={{marginLeft: "36px"}}
        >
          <Radio value="1">内置表单</Radio>
          <Radio value="2">外置表单</Radio>
          {!isCanvas && <Radio value="3">已有表单</Radio>}
        </Radio.Group>
      </div>
    );

    const Columns = activeKey === "1" ? this.columns : this.columnsExternal;

    return (
      <Modal
        title={title}
        visible={visible}
        onOk={activeKey === "1" ? this.handleOk : this.handleFormOk}
        onCancel={this.handleCancel}
        wrapClassName={styles.wrap}
        width={768}
        okText="确认"
        cancelText="取消"
      >
        {activeKey === "1" && (
          <>
            <div className={styles.search_bar}>
              <Input
                className={styles.search_input}
                onChange={this.handleInputChange}
                placeholder="请输入表单名称或编码查询"
              />
              <Button type="primary" onClick={this.handleSearch}>
                查询
              </Button>
            </div>
            <Table
              dataSource={listData}
              columns={Columns}
              onChange={this.handleTableChange}
              loading={dataLoading}
              size="small"
              rowKey="formKey"
              pagination={{
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ["6", "10", "20", "30"],
                current: pageNum,
                pageSize,
                total: totalCount,
              }}
              rowSelection={{
                hideDefaultSelections: true,
                columnWidth: 1,
                selectedRowKeys: [rowKey],
              }}
              onRow={record => {
                return {
                  onClick: () => {
                    const {formKey} = record;
                    let newValue = [formKey];
                    if (selectedRowKeys.some(ele => ele === formKey)) {
                      newValue = [];
                    }
                    this.setState({
                      selectedRowKeys: newValue,
                      selectFormData: record,
                    });
                  }, // 点击行
                };
              }}
            />
          </>
        )}
        {activeKey === "2" && (
          <Spin spinning={false}>
            <Form>
              <Form.Item
                label={
                  <span>
                  获取外置表单地址的接口&nbsp;
                    <Tooltip title="接口请求方式为get">
                    <Icon type="question-circle-o"/>
                  </Tooltip>
                </span>}
                {...formItemLayout}
              >
                {getFieldDecorator("formDescriptionUrl", {
                  initialValue: formDescriptionUrl,
                  rules: [
                    {required: true, message: "请输入获取外置表单地址的接口"},
                  ],
                })(<Input placeholder="请输入获取外置表单地址的接口"/>)}
              </Form.Item>
              {!isCanvas && (
                <Form.Item {...buttonItemLayout}>
                  <Button type="primary" ghost onClick={this.viewForm}>
                    查看表单解析内容
                  </Button>
                </Form.Item>
              )}
              {!isCanvas && (
                <Form.Item
                  label="选择流程处理界面iframe样式类型"
                  {...formItemLayout2}
                >
                  {getFieldDecorator("displayStyle", {
                    initialValue: displayStyle,
                    rules: [
                      {
                        required: true,
                        message: "请选择流程处理界面iframe样式类型",
                      },
                    ],
                  })(
                    <Select
                      placeholder="请选择流程处理界面iframe样式类型"
                      onChange={this.handleChange}
                    >
                      <Option value="standard">MOM审批标准iframe</Option>
                      <Option value="empty">业务自定义表单空白iframe</Option>
                    </Select>,
                  )}
                </Form.Item>
              )}
              {!isCanvas && selected === "standard" && (
                <Form.Item>
                  {getFieldDecorator("showAsUrl", {
                    valuePropName: "checked",
                    initialValue: showAsUrl === "Y",
                  })(
                    <Checkbox style={{marginLeft: "100px"}}>
                      业务表单是否以URL跳转形式展示
                    </Checkbox>,
                  )}
                  <Popover
                    placement="bottom"
                    content={
                      <div style={{width: 300}}>
                        由于业务表单可能非常复杂，可以选择以url形式在前端呈现，点击url可打开新链接查看业务表单
                      </div>
                    }
                  >
                    <Icon type="question-circle"/>
                  </Popover>
                </Form.Item>
              )}
            </Form>
          </Spin>
        )}

        {activeKey === "3" && (
          <Spin spinning={false}>
            <Form>
              <Form.Item label="选择已有表单" {...formItemLayout3}>
                {getFieldDecorator("existingForm", {
                  rules: [{required: true, message: "请选择已有表单"}],
                })(
                  <Select
                    placeholder="请选择已有表单"
                    onFocus={this.handleFocus}
                  >
                    {result
                      .filter(k => k.formname && k.formname !== "")
                      .map(item => (
                        <Option
                          key={item.name}
                          value={JSON.stringify(item)}
                        >
                          {`${item.isexecutable === true ? "流程" : "节点"}：${
                            item.name
                          }，表单：${item.formname}`}

                        </Option>
                      ))}
                  </Select>,
                )}
              </Form.Item>
              <Form.Item>
                {getFieldDecorator("existingDisplayStyle", {
                  valuePropName: "checked",
                })(
                  <Checkbox
                    style={{marginLeft: "100px"}}
                    onChange={this.handleCheckOnChange}
                  >
                    是否使用审批标准iframe
                  </Checkbox>,
                )}
              </Form.Item>
              {checked === true && (
                <Form.Item>
                  {getFieldDecorator("existingShowAsUrl", {
                    valuePropName: "checked",
                  })(
                    <Checkbox style={{marginLeft: "100px"}}>
                      是否以URL跳转方式展示
                    </Checkbox>,
                  )}
                  <Popover
                    placement="bottom"
                    content={
                      <div style={{width: 300}}>
                        由于业务表单可能非常复杂，可以选择以url形式在前端呈现，点击url可打开新链接查看业务表单
                      </div>
                    }
                  >
                    <Icon type="question-circle"/>
                  </Popover>
                </Form.Item>
              )}
            </Form>
          </Spin>
        )}
        {viewFormVisible && (
          <Modal
            width={800}
            visible={viewFormVisible}
            title="表单解析内容"
            onCancel={() => {
              this.handleViewFormVisible(false);
            }}
            footer={[
              <Button
                key="back"
                onClick={() => {
                  this.handleViewFormVisible(false);
                }}
              >
                关闭
              </Button>,
            ]}
          >
            <ReactJson
              src={formContent}
              name={false}
              displayDataTypes={false}
            />
          </Modal>
        )}
      </Modal>
    );
  }
}

export default FlowFormSelect;
